from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

from interface.models import Interface
from utils.common import result, format_to_request_param

# Create your views here.

# 分页 + 接口名模糊查询
def get(request):
    page = request.GET.get("page", 1)
    size = request.GET.get("size", 10)
    name = request.GET.get("name", "")
    interfaces = Interface.objects.filter(is_delete=False, name__contains=name)
    interface_page = Paginator(interfaces, size)
    interface_list = []
    for interface in interface_page.page(page):
        interface_list.append({
            'id': interface.id,
            'name': interface.name,
            'project_id': interface.project_id,
            'project_name': interface.project_name,
            'module_id': interface.module_id,
            'module_name': interface.module_name,
            'author': interface.author,
            'request': interface.request
        })
    result["data"] = {
        "list": interface_list,
        "pages": interface_page.num_pages,
        "total": interface_page.count
    }
    return JsonResponse(result, safe=False, status=200)


# 创建数据
def post(request):
    try:
        json_data = request.body.decode('utf-8')
        if json_data:
            python_data = eval(json_data)
            Interface.objects.create(**python_data)
            print(python_data)
            # python_data['request'] = str(python_data['request'])
            python_data['request'] = ''
            print(python_data)
            Interface.objects.create(**python_data)
            result["message"] = "保存成功"
            result["success"] = True
            return JsonResponse(result, status=200)
    except Exception as e:
        result["message"] = e
        return JsonResponse(result,  safe=False, status=200)